<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, unref } from 'vue';
  import { modalFormSchema } from './data';
  import mcApi from 'mc-c2b2m-operator-api';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useUserStore } from '@/store/modules/user';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModalInner } from '@/components/Modal';

  const { SystemModule } = mcApi;
  const { DepartmentApi } = SystemModule;

  const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: modalFormSchema,
    baseColProps: { span: 22 },
    showActionButtonGroup: false,
  });

  const ifUpdate = ref<boolean>(false);
  const [registerModal, { setModalProps }] = useModalInner(async (data) => {
    await resetFields();
    ifUpdate.value = !!data.ifUpdate;
    setModalProps({
      minHeight: 250,
      destroyOnClose: true,
      confirmLoading: false,
      title: `${ifUpdate.value ? '编辑' : '添加'}部门`,
    });
    if (unref(ifUpdate)) {
      const { record } = data;
      const { parentId, parentName } = record;
      await setFieldsValue({
        ...record,
        parentId: parentId ? [{ label: parentName, value: parentId }] : [],
      });
    }
  });

  const { createMessage } = useMessage();
  const emits = defineEmits(['success']);

  const userStore = useUserStore();
  const orgId: string = userStore.getUserInfo.orgId;

  async function handleOk() {
    try {
      await validate();
      const values = getFieldsValue();
      values.orgId = orgId;
      const { parentId } = values;
      parentId?.length && (values.parentId = parentId[0].value);
      setModalProps({ confirmLoading: true });
      const fun = unref(ifUpdate)
        ? DepartmentApi.updateOrgDepartment
        : DepartmentApi.createOrgDepartment;
      await fun(values);
      createMessage.success(`${unref(ifUpdate) ? '编辑' : '新增'}成功！`);
      emits('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style scoped lang="less"></style>
